﻿using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

partial struct BulletMoveSystem : ISystem
{

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        EntityCommandBuffer entityCommandBuffer =
            SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>().CreateCommandBuffer(state.WorldUnmanaged);
        foreach ((RefRW<LocalTransform> localTransform, RefRO<Bullet> bullet, RefRO<Target> target, Entity entity)
            in SystemAPI.Query<RefRW<LocalTransform>, RefRO<Bullet>, RefRO<Target>>().WithEntityAccess())
        {
            if (target.ValueRO.tagertEntity == Entity.Null)
            {
                UnityEngine.Debug.Log("Destory");
                entityCommandBuffer.DestroyEntity(entity);
                continue;
            }

            LocalTransform targetLocalTransform = SystemAPI.GetComponent<LocalTransform>(target.ValueRO.tagertEntity);
            ShootVictim targetVictimPostion = SystemAPI.GetComponent<ShootVictim>(target.ValueRO.tagertEntity);
            float3 targetPostion = targetLocalTransform.TransformPoint(targetVictimPostion.targetPostion);

            float distanceBeforeSq = math.distancesq(localTransform.ValueRO.Position, targetPostion);

            float3 moveDirection = math.normalize(targetPostion - localTransform.ValueRO.Position);
            localTransform.ValueRW.Position += moveDirection * SystemAPI.Time.DeltaTime * bullet.ValueRO.speed;

            float distanceAfterSq = math.distancesq(localTransform.ValueRO.Position, targetPostion);

            if (distanceAfterSq > distanceBeforeSq)
            {
                localTransform.ValueRW.Position = targetPostion;
            }

            float destoryDistance = .2f;
            if (math.distancesq(targetPostion, localTransform.ValueRO.Position) < destoryDistance)
            {
                RefRW<Health> health = SystemAPI.GetComponentRW<Health>(target.ValueRO.tagertEntity);
                health.ValueRW.healthAmount -= bullet.ValueRO.damageAmount;
                health.ValueRW.onHealthChanged = true;
                entityCommandBuffer.DestroyEntity(entity);
            }
        }
    }

}
